package com.demo.dao;

import com.demo.domain.Student;
import com.demo.util.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

public class StudentDao {
    //检查学生是否存在的方法
    public boolean daoCheck(String username) throws SQLException {
        //1.获取连接池DataSource对象
        DataSource dataSource = JDBCUtils.getDataSource();
        //2.使用DBUtils
        QueryRunner qr = new QueryRunner(dataSource);
        //3.查询操作
        Long count = (Long) qr.query("select count(*) from student where username = ? ", new ScalarHandler(), username);
        //4.如果查到了
        return count >= 1;
    }

    //删除学生
    public boolean daoDelete(String id) throws SQLException {
        DataSource dataSource = JDBCUtils.getDataSource();

        QueryRunner qr = new QueryRunner(dataSource);

        String sql = "delete from student where id = ?";

        //如果只有一个参数的话 不需要创建数组
        qr.update(sql, Integer.parseInt(id));
        return true;
    }

    //检查学生登陆是否成功的方法
    public boolean daoLogin(String username, String password) throws SQLException {
        DataSource dataSource = JDBCUtils.getDataSource();
        QueryRunner qr = new QueryRunner(dataSource);
        //查询操作
        Long count = (Long) qr.query("select count(*) from student where username = ?  and  password = ?", new ScalarHandler(), username, password);
        //如果查到了
        return count >= 1;
    }

    //注册
    public boolean daoRegister(String username, String password, String num, String name, String sex, String birthDay) throws SQLException {
        DataSource dataSource = JDBCUtils.getDataSource();
        QueryRunner qr = new QueryRunner(dataSource);
        String sql = "insert into student values(?,?,?,?,?,?,?)";
        Object[] param = {null, username, password, num, name, Integer.parseInt(sex), birthDay};
        int i = qr.update(sql, param);
        return true;
    }

    //获取学生列表
    public List<Student> daoGetList() throws SQLException {
        DataSource dataSource = JDBCUtils.getDataSource();
        QueryRunner qr = new QueryRunner(dataSource);
        String sql = "select * from student";
        List<Student> query = qr.query(sql, new BeanListHandler<Student>(Student.class));

        return query;
    }

}
